﻿using MslDiary.BLL;
using MslDiary.Utils;
using System;
using System.Collections.Generic;
using System.Windows.Input;
using MFW = MslDiary.Framework;

namespace MslDiary.ViewModel
{
    public class ConfigViewModel : MslDiary.Framework.ViewModelBase
    {
        private MFW.IO.ConfigHelper config = new MFW.IO.ConfigHelper(MFW.Gloable.Config);
        private MFW.Tool.SysHelper sys = new MFW.Tool.SysHelper();
        private A_UserBLL userBLL = new A_UserBLL();
        private MslDiary.Model.A_User mod = new Model.A_User();
        private System.Windows.Window win = null;

        public ConfigViewModel()
        {
            this.LstMinute = new List<int> { 
                1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
            };

            this.WindowLoadCommand = new CommandBase((Object window) =>
            {
                if (window != null)
                    this.win = window as System.Windows.Window;
                Load();
            });
            this.SaveCommand = new CommandBase((Object m) => Save());
            this.ModifyPwdCommand = new CommandBase((Object m) => this.IsModifyLoginPwd = !IsModifyLoginPwd);
            this.CancleCommand = new CommandBase((Object m) =>
            {
                if (m == null)
                    return;
                System.Windows.Window win = (System.Windows.Window)m;
                if (win != null)
                    win.Hide();
            });
            this.SelectionMinuteChangedCommand = new CommandBase((Object m) =>
            {
                this.LeaveMinuteLock = (Int32)m;
            });
        }

        #region 属性

        private string _oncePwd;
        private string _secondPwd;
        private int _leaveMinuteLock = 1;
        private bool _isAutoRun;
        private bool _autoCheckUpdate;
        private bool _minimizeToTray;
        private bool _isAutoLock = true;
        private bool _minimizeToAutoLock = true;
        private string _loginedAccount;
        private string _nickName;
        private string _dataBasePwd;
        private string _onceDataBasePwd;
        private string _twoDataBasePwd;
        private bool _isModifyLoginPwd = false;
        ///<summary></summary>
        public bool IsModifyLoginPwd
        {
            get { return _isModifyLoginPwd; }
            set
            {
                //base.SetProperty<bool>(ref this._isModifyLoginPwd, value);
                if (this._isModifyLoginPwd == value)
                    return;
                this._isModifyLoginPwd = value;
                this.RaisePropertyChanged("IsModifyLoginPwd");
            }
        }
        ///<summary></summary>
        public string TwoDataBasePwd
        {
            get { return _twoDataBasePwd; }
            set
            {
                //base.SetProperty<string>(ref this._twoDataBasePwd, value);
                if (this._twoDataBasePwd == value)
                    return;
                this._twoDataBasePwd = value;
                this.RaisePropertyChanged("TwoDataBasePwd");
            }
        }
        /// <summary> 自动锁定时间 </summary>
        public List<int> LstMinute { get; set; }
        ///<summary></summary>
        public string OnceDataBasePwd
        {
            get { return _onceDataBasePwd; }
            set
            {
                //base.SetProperty<string>(ref this._onceDataBasePwd, value);
                if (this._onceDataBasePwd == value)
                    return;
                this._onceDataBasePwd = value;
                this.RaisePropertyChanged("OnceDataBasePwd");
            }
        }
        ///<summary>数据库密码</summary>
        public string DataBasePwd
        {
            get { return _dataBasePwd; }
            set
            {
                //base.SetProperty<string>(ref this._dataBasePwd, value);
                if (this._dataBasePwd == value)
                    return;
                this._dataBasePwd = value;
                this.RaisePropertyChanged("DataBasePwd");
            }
        }
        ///<summary>登录帐号</summary>
        public string LoginedAccount
        {
            get { return _loginedAccount; }
            set
            {
                //base.SetProperty<string>(ref this._loginedAccount, value);
                if (this._loginedAccount == value)
                    return;
                this._loginedAccount = value;
                this.RaisePropertyChanged("LoginedAccount");
            }
        }
        ///<summary></summary>
        public string NickName
        {
            get { return _nickName; }
            set
            {
                //base.SetProperty<string>(ref this._nickName, value);
                if (this._nickName == value)
                    return;
                this._nickName = value;
                this.RaisePropertyChanged("NickName");
            }
        }
        /// <summary></summary>
        public bool MinimizeToAutoLock
        {
            get { return _minimizeToAutoLock; }
            set
            {
                //base.SetProperty<bool>(ref this._minimizeToAutoLock, value);
                if (this._minimizeToAutoLock == value)
                    return;
                this._minimizeToAutoLock = value;
                this.RaisePropertyChanged("MinimizeToAutoLock");
            }
        }
        /// <summary></summary>
        public bool IsAutoLock
        {
            get { return _isAutoLock; }
            set
            {
                //base.SetProperty<bool>(ref this._isAutoLock, value);
                if (this._isAutoLock == value)
                    return;
                this._isAutoLock = value;
                this.RaisePropertyChanged("IsAutoLock");
            }
        }
        /// <summary></summary>
        public bool MinimizeToTray
        {
            get { return _minimizeToTray; }
            set
            {
                //base.SetProperty<bool>(ref this._minimizeToTray, value);
                if (this._minimizeToTray == value)
                    return;
                this._minimizeToTray = value;
                this.RaisePropertyChanged("MinimizeToTray");
            }
        }
        /// <summary>是否自动检查更新</summary>
        public bool AutoCheckUpdate
        {
            get { return _autoCheckUpdate; }
            set
            {
                //base.SetProperty<bool>(ref this._autoCheckUpdate, value);
                if (this._autoCheckUpdate == value)
                    return;
                this._autoCheckUpdate = value;
                this.RaisePropertyChanged("AutoCheckUpdate");
            }
        }
        /// <summary>是否自动启动</summary>
        public bool IsAutoRun
        {
            get { return _isAutoRun; }
            set
            {
                //base.SetProperty<bool>(ref this._isAutoRun, value);
                if (this._isAutoRun == value)
                    return;
                this._isAutoRun = value;
                this.RaisePropertyChanged("IsAutoRun");
            }
        }
        /// <summary></summary>
        public int LeaveMinuteLock
        {
            get { return _leaveMinuteLock; }
            set
            {
                //base.SetProperty<int>(ref this._leaveMinuteLock, value);
                if (this._leaveMinuteLock == value)
                    return;
                this._leaveMinuteLock = value;
                this.RaisePropertyChanged("LeaveMinuteLock");
            }
        }
        /// <summary></summary>
        public string SecondDiaryLockPwd
        {
            get { return _secondPwd; }
            set
            {
                //base.SetProperty<string>(ref this._secondPwd, value);
                if (this._secondPwd == value)
                    return;
                this._secondPwd = value;
                this.RaisePropertyChanged("SecondDiaryLockPwd");
            }
        }
        /// <summary></summary>
        public string OnceDiaryLockPwd
        {
            get { return _oncePwd; }
            set
            {
                //base.SetProperty<string>(ref this._oncePwd, value);
                if (this._oncePwd == value)
                    return;
                this._oncePwd = value;
                this.RaisePropertyChanged("OnceDiaryLockPwd");
            }
        }
        #endregion

        #region 命令
        /// <summary> 锁屏  </summary>
        public ICommand SelectionMinuteChangedCommand { set; get; }
        /// <summary>保存</summary>
        public ICommand SaveCommand { get; set; }
        /// <summary>取消</summary>
        public ICommand CancleCommand { get; set; }
        public ICommand WindowLoadCommand { get; set; }
        /// <summary>修改密码</summary>
        public ICommand ModifyPwdCommand { get; set; }

        #endregion

        #region 方法

        private void Load()
        {
            this.MinimizeToTray = MFW.Gloable.MinimizeToTray;
            if (!String.IsNullOrEmpty(MFW.Gloable.DiaryLockPwd))
                this.OnceDiaryLockPwd = this.SecondDiaryLockPwd = MFW.Gloable.DiaryLockPwd;

            this.IsAutoLock = String.IsNullOrEmpty(MFW.Gloable.DiaryLockPwd) ? false : true;
            this.AutoCheckUpdate = MFW.Gloable.AutoCheckUpdate;
            this.LeaveMinuteLock = MFW.Gloable.LeaveTimeToLock / 60;
            this.MinimizeToAutoLock = MFW.Gloable.MinimizeToAutoLock;
            this.LoginedAccount = MFW.Gloable.CurrentLoginedAccount;
            this.NickName = MFW.Gloable.NickName;

            //自动启动
            if (this.sys.IsAutoStartup())
                this.IsAutoRun = true;
        }
        private void Save()
        {
            if (!CheckLockPwd()) return;
            if (!CheckDbLoginPwd()) return;
            this.sys.AutoStartup(this.IsAutoRun);
            try
            {
                this.config.SetValueByKey("MinimizeToTray", this.MinimizeToTray ? "1" : "0");
                this.config.SetValueByKey("AutoCheckUpdate", this.AutoCheckUpdate ? "1" : "0");
                this.config.SetValueByKey("IsAutoRun", this.IsAutoRun ? "1" : "0");
                this.config.SetValueByKey("MinimizeToAutoLock", this.MinimizeToAutoLock ? "1" : "0");

                this.config.Save();

                #region 更新 A_User 表

                mod = userBLL.GetModelByAccount(MFW.Gloable.CurrentLoginedAccount);
                mod.NickName = this.NickName;
                if (this.IsAutoLock)
                {
                    if (mod != null && mod.Id != 0)
                    {
                        this.OnceDiaryLockPwd = MSL.Tool.Security.DESEncrypt.Instance.Encrypt(this.OnceDiaryLockPwd.Trim(), Framework.Gloable.NormalEncryptKey);
                        mod.DiaryIsLock = "1";
                        mod.DiaryLockPwd = this.OnceDiaryLockPwd.Trim();
                        mod.LeaveTimeToLock = this.LeaveMinuteLock * 60;
                    }
                }
                else
                {
                    this.OnceDiaryLockPwd = this.SecondDiaryLockPwd = "";
                    if (mod != null && mod.Id != 0)
                    {
                        mod.DiaryIsLock = "";
                        mod.DiaryLockPwd = "";
                    }
                }
                if (this.userBLL.Update(this.mod, " Id=" + mod.Id) <= 0)
                {
                    MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.SAVE_MSG02);
                    return;
                }
                #endregion

                #region 保存登录信息到文件 user.xml
                bool modifydbResult = false;
                if (this.IsModifyLoginPwd && !String.IsNullOrEmpty(this.OnceDataBasePwd))
                {
                    modifydbResult = MSL.Tool.Data.DbHelper.Instance.ChangePassword(this.OnceDataBasePwd);
                    this.userBLL.SaveEncryptPwdToFile(MslDiary.Framework.Gloable.CurrentLoginedAccount, this.OnceDataBasePwd);
                }
                string path = MFW.Gloable.StartPath + "\\data\\user.xml";
                MFW.IO.ConfigHelper userConfig = new MFW.IO.ConfigHelper(path);
                string aPath = "User/Name[@account='" + this.LoginedAccount + "']";
                userConfig.SetAttribute(
                    aPath,
                    "pwd",
                    MslDiary.Framework.Helper.EncryptDbPwd(MslDiary.Framework.Gloable.CurrentLoginedAccount, this.OnceDataBasePwd)
                    );
                userConfig.Save();
                if (modifydbResult)
                {
                    MslDiary.Utils.Helper.Instance.AlertConfirm("提示", "密码修改成功，重启后生效！", () =>
                     {
                         Helper.Instance.ExitApp();
                         return;
                     });
                }
                #endregion

                MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.SAVE_MSG01);

                #region 重新读取配置

                Helper.Instance.ReadConfig();
                this.userBLL.ReadUserInfo(mod);
                this.SecondDiaryLockPwd = this.OnceDiaryLockPwd;
                #endregion
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog("Config Save\r\n" + ex.ToString());
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
            }
        }
        private bool CheckLockPwd()
        {
            string msg = String.Empty;
            if (this.IsAutoLock)
            {
                if (String.IsNullOrEmpty(this.OnceDiaryLockPwd) || String.IsNullOrEmpty(this.SecondDiaryLockPwd))
                    msg = "锁定密码不能为空！";
                else if (!this.OnceDiaryLockPwd.Equals(this.SecondDiaryLockPwd))
                    msg = "两次锁定密码不一致！";
                else if (this.LeaveMinuteLock == 0)
                    msg = "时间不能为0！";
            }
            if (!String.IsNullOrEmpty(msg))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning(msg);
                return false;
            }
            return true;
        }
        private bool CheckDbLoginPwd()
        {
            string msg = String.Empty;
            if (this.IsModifyLoginPwd)
            {
                if (!String.IsNullOrEmpty(this.DataBasePwd) && !String.IsNullOrEmpty(this.OnceDataBasePwd))
                {
                    if (this.TwoDataBasePwd == null)
                        msg = "再次登录密码不能为空！";
                    else if (!MFW.Gloable.DiaryLoginPwd.Equals(this.DataBasePwd))
                        msg = "原始登录密码不正确！";
                    else if (MFW.Gloable.DiaryLoginPwd.Equals(this.OnceDataBasePwd))
                        msg = "新密码不能和原始密码相同！";
                    else if (!this.OnceDataBasePwd.Equals(this.TwoDataBasePwd))
                        msg = "两次登录密码不一致！";
                }
                if (!String.IsNullOrEmpty(msg))
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning(msg);
                    return false;
                }
            }
            return true;
        }
        #endregion
    }
}
